<?php

namespace Course\Controller;
use Think\Page;
use Think\Controller;


/**
 * 集体备课控制器
 * @author水月居 <singliang@163.com>
 */
class WckczuoyeController extends Controller {
	public function _initialize()
    {
       header("Content-type: text/html; charset=utf-8");
       $uid=is_login();
       // if($uid){
       //  $my=query_user(array('nickname'));
       //  $my['uid']=$uid;
       //  $this->assign(my,$my);               
       //    }else{
       //    $this->error('请先登录',U('ucenter/member/login'),1);
       //  } 


        //准备公用数据模型列表	
        $this->fileModel=D('Course/WckcStFiles');
        //dump( $this->fileModel);
        $this->courseModel=D('WckcCourse');
        $courselist=$this->courseModel->where(array('satus'=>1))->order(array('sort'=>'asc'))->field('status',true)->select();      
        $this->assign('courselist',$courselist);
       // dump($courselist);die;
        $this->studentModel=D('WckcStudent');
        $studentlist=$this->studentModel->where(array('satus'=>1))->field('id,bj_code,st_code,st_name')->select();
        //dump($studentlist) ;die;     
        $this->assign('studentlist',$studentlist);
        $this->_ROOTPATH='./Uploads/Wckczuoye/';
        C('_ROOTPATH','./Uploads/Wckczuoye/');
    }

    /**
     * 作业上传首页
    */
    public function index(){
    	$cateModel=$this->studentModel;
    	$sublist=$cateModel->order(array('id'=>'asc'))
    	         ->where(array('satus'=>1))->field('id,cate')->select();
 
	    $fileModel=$this->fileModel;
	    $order=array('create_time'=>'desc');
	     $newlist=$fileModel->field("id,title,bj_code,bj_name,st_name,update_time")->order($order)->limit('0,6')->select();
	     $data[]=array(
	     	'id'      =>0,
	     	'cate'    =>'最近上传',
	     	'postlist'=>$newlist,
	     );
	    foreach($sublist as $key => $value){
	    	$value['postlist']=$fileModel
	    	->field('id,title,teacher,group,update_time')
	    	->limit(6)->order($order)
	    	->where(array('cid'=>$value['id']))->select();
	    	$data[]=$value;
	    	
	    }

//p($data);
	    $this->assign('list', $data);
        $this->display();
    }


    /*上传作业文件*/
    public function addFile(){


		 if(IS_POST){
		 //post检测
		 $cid=I('cid');
		 //dump($cid);
		 $course=$this->courseModel->getFieldById($cid,'title');
		 //dump($course);die;
		 	$year=I('post.year',0,'intval');
		 	$title=I('post.title');
		 	$st_code=I('post.st_code');
            $map['st_code']=$st_code;
      //dump($st_code);
		 	//$username=I('teacher');
		 	// $group=I('post.group');
    //         if(!$_POST['group']){
    //             $this->error("请选择上传组别后再上传",Cookie('__forward__'),3);
    //             }
            if(!$title){
                $this->error("请检查标题是否填写完整",Cookie('__forward__'),3);
                }                               
	       	if(!$st_code){
	          $this->error("请先选择姓名后再上传",Cookie('__forward__'),3);
	       	}else{
            $aStudent= $this->studentModel->where($map)->find();
			$st_name=$aStudent['st_name'];
			$bj_name=$aStudent['bj_name'];
			$bj_code=$aStudent['bj_code'];
          }
	       	$rootpath=C('_ROOTPATH');
          //$aStudent= $this->studentModel->where($map)->find();

	   if(!file_exists($rootpath)) {		    
		 mkdir($rootpath);//如果不存在则设定目录
		  echo '目录创建成功';//die;
     	}
	       // $info=$this->cateModel->find($cid);
	       // $cate= $info['cate'];
	       // $savepath=$info['savepath'];
	       $fileModel=$this->fileModel;
		   $savePath=$bj_code.'/';
	       //$savepath.='/';
	       $save_name= $title.$bj_name.$st_name.uniqid();
		   $subName = C('CUR_TERM');
	       $config = array(
	            'maxSize'    =>   20*1024*1024, // 设置附件上传大小
	            'rootPath'   =>    $this->_ROOTPATH,
	            'savePath'   =>    $savePath,
	            'saveName'   =>   iconv('utf-8', 'gbk', $save_name),//$save,// uniqid(),//
	            'exts'       =>    array('jpg', 'png', 'zip', 'rar', 'doc', 'docx','pdf','gif','fla','swf'),
	            'autoSub'    =>    true,
	            'subName'    =>    $subName,
             );
         //dump($aStudent);
         //dump($config);die;

          $upload = new \Think\Upload($config);// 实例化上传类 
          $info   =  $upload->upload();
			    $file_ext = pathinfo($_FILES['upfile']['name'], PATHINFO_EXTENSION );

			if(!$info) {
				        // 上传错误提示错误信息
				        $this->error($upload->getError(),Cookie('__forward__'),3);
				       }else{
                    // 上传成功保存表单数据				       
				    //$url= $info['upfile']['savepath'].$info['upfile']['savename'];  
                    $url=$savePath.$subName.'/'.$save_name.'.'.$file_ext;			
				    $data=array(
			   'course'      => $course,
			   'bj_code'	=> $bj_code, 
               'st_code'	=> $st_code,			   
               'term'       => C('CUR_TERM'),
			   "bj_name"    => $bj_name, 
               "st_name"    => $st_name,                         
               "title"      => $title,
			   'keywords'   => $bj_name.','.C('CUR_TERM').','.$bj_code.','.$title.','.$st_name,				         
               "file_url"   => $url,                       
               "file_name"  => $_FILES['upfile']['name'],
               'file_ext'   => $file_ext,
               "title"      => I('post.title'),
               //"year"       => C('CUR_TERM'),
				     );
				 
//dump($data);
				 $data=$fileModel->create($data);
 //dump($data);die;

		         if($fileModel->add()){ 
		            $this->success('上传成功！');		         	
		         }else{
		         	$this->success('保存失败！');
		         }
		       }
		   }


       $this->display();
	}

/*编辑课程信息*/
  public function editCourse()
  {

      $courseModel=$this->courseModel;

        $id=I('get.id');
        if($id){
        $aInfo=$courseModel->field('status',true)->find($id);//排除指定项其他都选取
        $this->assign('info',$aInfo);
        $this->assign('title','<i class="icon icon-edit"></i> 编辑课程，点击右边添加新课程');

        }else{

         $this->assign('title','<i class="icon icon-plus"></i> 新增课程，点击左边对应课程别编辑');
        }

      if(IS_POST){
      	$id=I('id',0,'intval');
      	// $group=I('post.group');
  	    // if(!$group){
  	    //   $this->error('请填写组别名称，再操作！',U('Course/Wckczuoye/editCourse'));
  	    // }
  	    
  	    $data=I('post.');
  	   // dump($data);die;
  	   //$data= $cateModel->create($data);
  	    //dump($data);die;
    	    if($id){
    	    	$data= $courseModel->create($data);
    	    	$courseModel->save();
    	    	$this->success('更新成功！');
    	    }else{
    	    	unset($data['id']);
    	    	$data['status']=1;
    	    	
    	    	$data= $courseModel->create($data);
    	    	//dump($data);
    	    	$aid=$courseModel->add($data);
    	    	//p($groupModel->getLastSql());
    	    	//$cateModel->error();
    	    	// dump($data);die;
    	    	$this->success('添加成功！');
    	    }
        
      }
    $this->display();
  }

/*编辑上传资料*/
  public function edit()
  {
  
  $id=I('get.id');
  $fileModel=$this->fileModel;
  $postinfo=$fileModel->field('s_key',true)->find($id);//排除指定项其他都选取
  //dump($postinfo);
  //dump($uid);
  if(!$postinfo){
    $this->error('参数错误');
  }else{
    $uid=is_login();
    if($uid!=$postinfo['uid']){
      $this->error('对不起，您不能修改别人上传的资料！');
    }
    $this->assign('info',$postinfo);
  }

    if(IS_POST){
      $fileModel->create(I('post.'));
      $fileModel->save();
      $this->success('更新成功！');
    }
  $this->display();
  }

	/**@水月居
	*我的上传*
	**/
	public function myupload($uid=0)
	{
	  	$uid=is_login();
	  	$map['uid'] = $uid;
      $order=array('create_time'=>'desc','group'=>'desc','cid'=>'desc');
	    $list=$this->fileModel->where($map)->order($order)->select();
	    $this->assign('list',$list);
	  $this->display();
	 }
   /**@todo
	*显示文档详情*
	**/
  public function detail($id=0) {
    $post_id=I('get.id'); 
    $post=$this->fileModel->find($post_id);
    $this->assign('alist',$post);
    $this->display();
  }
   /**@todo
  *下载附件*
  **/
   public function download(){
    $id=I('fid');
    $afile=$this->fileModel->find($id);

    //判断文件是否存在
    $file_path = C('_ROOTPATH').$afile['file_url'];
    
    $file_path = iconv('utf-8', 'gb2312', $file_path); //对可能出现的中文名称进行转码
    if (!file_exists($file_path)) {
      $this->error('文件不存在！');
    }
    $file_name =$afile['file_name']; //获取文件名称 basename()
    $file_size = filesize($file_path); //获取文件大小
    $fp = fopen($file_path, 'r'); //以只读的方式打开文件
    header("Content-type: application/octet-stream");
    header("Accept-Ranges: bytes");
    header("Accept-Length: {$file_size}");
                 if (preg_match('/MSIE/', $_SERVER['HTTP_USER_AGENT'])) { //for IE
                 header('Content-Disposition: attachment; filename="' . rawurlencode($file_name) . '"');
             } else {
                 header('Content-Disposition: attachment; filename="' . $file_name . '"');
             }
    //header("Content-Disposition: attachment;filename={$file_name}");
    $buffer = 1024;
    $file_count = 0;
    //判断文件是否结束
    while (!feof($fp) && ($file_size-$file_count>0)) {
    $file_data = fread($fp, $buffer);
    $file_count += $buffer;
    echo $file_data;
    }
    fclose($fp); //关闭文件
    }
    /**
    * 删除文件
    * @param string $filename
    */
   public function delFile($fileid) {
    if (file_exists($filename)) unlink($filename);
    }
     
	/**todo
	*资料查询
	*/
   public function search(){

   	/**查询字段条件拼组**/ 
    $map['status']=1;
    $search=I('keywords');
    $group=I('post.group');
    $subject=I('post.subject');
    if(!empty($search)){
      $map['keywords'] = array('like','%'.$search.'%');
    }else{
      unset($map['keywords']);
    }
   if('所有组别'==$group||empty($group)){
    unset($map['group']);
   }else{
    $map['group']=I('group');
   }

  
  //P($map);//die;
   	//like模糊查询
   	$searchlist=$this->fileModel->field('status,cid,s_key',true)->order('update_time desc')->where($map)->limit(20)->select();

     $this->assign('list',$searchlist);
     $this->assign('subjectlist',$sublist);
     $this->display();
   }


}